package de.unibielefeld.msp.zusatzstoffe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import de.unibi.techfak.msp.eatThis.bean.FoodBean;
import de.unibielefeld.msp.zusatzstoffe.utility.Constants;
import de.unibielefeld.msp.zusatzstoffe.utility.ServiceConsumer;
import flexjson.JSONDeserializer;

/**
 * Listen Durchsuchungs Activity.
 * 
 * @author Henry
 * 
 */
public class Foodlist extends Activity {
    private final static String TAG = "Foodlist";
    
    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.foodlist);

        new FoodListAsync().execute();
    }

    private class FoodListAsync extends AsyncTask<Void, Void, String> {

        private final ProgressDialog dialog = new ProgressDialog(Foodlist.this);

        // can use UI thread here
        @Override
        protected void onPreExecute() {
            this.dialog.setMessage("Waiting for data ...");
            // this.dialog.show();
        }

        @Override
        protected String doInBackground(Void... arg0) {
            HttpResponse response;
            String responseString = null;
            ResponseHandler<String> responseHandler;
            HttpGet url;

            try {

                url = new HttpGet(Constants.CONNECTION_PREFIX + "?listed=true");

                responseHandler = new BasicResponseHandler();

                response = ServiceConsumer.execute(url);

                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {

                    CharSequence text = "Something, somewhere went terribly wrong!";
                    Toast toast = Toast.makeText(getApplicationContext(), text,
                            Toast.LENGTH_SHORT);
                    toast.show();

                }

                responseString = responseHandler.handleResponse(response);

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return responseString;
        }

        @Override
        protected void onPostExecute(final String result) {
            if (this.dialog.isShowing()) {
                // TODO: MICHAAAAAAAAAA!
                this.dialog.dismiss();
            }
            // TODO Artikel nicht gefunden, wollen sie den Artikel eintragen?
            if (result == null) {
                CharSequence text = "Artikel nicht gefunden!";
                Toast.makeText(getApplicationContext(), text,
                        Toast.LENGTH_SHORT);
                return;
            }
            
            final List<FoodBean> foodList = new JSONDeserializer<List<FoodBean>>()
                    .deserialize(result);

            Log.d(TAG, foodList.toString());

            List<String> foodName = new ArrayList<String>();
            ArrayAdapter<String> foodAdapter = new ArrayAdapter<String>(
                    getBaseContext(), android.R.layout.simple_list_item_1);
            final HashMap<String, String> ingredients = new HashMap<String, String>();
            
            for (FoodBean fb : foodList) {
                foodName.add(fb.getName());
                foodAdapter.add(fb.getName());
                ingredients.put(fb.getName(), fb.getIngredients());
            }
            final ListView list = (ListView) findViewById(R.id.foodlistView);

            list.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    Bundle bundle = new Bundle();
                    bundle.putString("NAME",
                            (String) list.getItemAtPosition(arg2));
                    bundle.putString("INGREDIENTS",ingredients.get((String) list.getItemAtPosition(arg2)));
                    Intent intent = new Intent(getApplicationContext(),
                            FoodItem.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            });

            EditText search = (EditText) findViewById(R.id.foodSearchBar);
            search.addTextChangedListener(new TextWatcher() {

                public void onTextChanged(CharSequence s, int start,
                        int before, int count) {
                    ArrayAdapter<String> array = new ArrayAdapter<String>(
                            getBaseContext(),
                            android.R.layout.simple_list_item_1);
                    for (FoodBean fb : foodList) {
                        String name = fb.getName();
                        if (name.toLowerCase().contains(
                                s.toString().toLowerCase())) {
                            array.add(name);
                        }
                    }
                    list.setAdapter(array);
                }

                public void beforeTextChanged(CharSequence s, int start,
                        int count, int after) {
                }

                public void afterTextChanged(Editable s) {
                }
            });

            list.setAdapter(foodAdapter);
        }
    }
}